package Olivia.manager
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.utils.getQualifiedClassName;
	
	public class ResLoader extends EventDispatcher
	{
		private var _loader:Loader;
		
		private var _loading:Boolean;
		private var _url:String;
		private var _callBack:Function;
		private var _param:*;
		
		public function ResLoader()
		{
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeLoader);
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			
			_loading = false;
		}
		
		private function ioErrorHandler(e:IOErrorEvent):void
		{
			trace("ioErrorHandler: " + e);
		}
		
		private function completeLoader(e:Event):void
		{
			var content:* = (e.target as LoaderInfo).content;
			var returnRes:*;
			
			if(content is Bitmap)
			{
				ResManager.StoreList[_url] = (content as Bitmap).bitmapData;
				returnRes = new Bitmap(ResManager.StoreList[_url] as BitmapData);
			}
			else if(content is MovieClip)
			{
				var className:String = getClassName(_url);
				var MC:Class = (e.target as LoaderInfo).applicationDomain.getDefinition(className) as Class;
				ResManager.StoreList[_url] = MC;
				returnRes = new MC();
			}
			
			if(_callBack != null)
			{
				if(_param == null)
				{
					_callBack.call(null, returnRes);
				}
				else
				{
					_callBack.call(null, returnRes, _param);
				}
			}
			
			_loading = false;
			
			dispatchEvent(new Event(Event.COMPLETE));
			
			trace("resource load complete: " + _url);
		}
		
		public function load(url:String, callback:Function=null, param:*=null):void
		{
			_url = url;
			_callBack = callback;
			_param = param;
			
			_loader.load(new URLRequest(_url));
			_loading = true;
		}	
		
		private function getClassName(url:String):String
		{
			url = url.replace("/","\\");
			var arr:Array = url.split("\\");
			
			return (arr[arr.length-1] as String).split(".")[0];
		}
		
		public function get loading():Boolean
		{
			return _loading;
		}
		
		public function get URL():String
		{
			return _url;
		}
	}
}